<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\InvalidRequestException;
use App\Http\Controllers\Controller as BaseController;
use Illuminate\Support\Facades\Validator;

class Controller extends BaseController
{
    public $pageSize = 2;

    /**
     * 计算请求的分页数据
     * @param $request
     * @param $pageSize
     * @return mixed
     */
    public function handleRequestPage($request, $pageSize)
    {
        $request['page'] = !empty($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $request['offset'] = ($request['page'] - 1) * $pageSize;
        $request['pageSize'] = $pageSize;
        return $request;
    }

    /*
     * 表单数据验证
     * @param
     * $request => 接受的请求数据
     * $rules   => 验证规则
     */
    public function validatesRequests($data = [], $rules = [], $messages = [])
    {
        $validator = Validator::make($data, $rules, $messages);

        if ($validator->fails()) {
            //abort(422, $validator->errors()->first());
            throw new InvalidRequestException($validator->errors()->first(), 422);
        }
        return $validator;
    }

    public function success($message = '成功',array $data = [], array $headers = [], $options = 0)
    {
        return response()->json([
            'code' => 200,
            'message' => $message,
            'data' => $data ?: new \stdClass()
        ], $status = 200, $headers, $options);
    }

    public function error($code = 400, $message = '失败',array $data = [], array $headers = [], $options = 0)
    {
        return response()->json([
            'code' => $code,
            'message' => $message,
            'data' => $data ?: new \stdClass()
        ], $status = 200, $headers, $options);
    }
}
